package com.googlecode.imanager.client.form;

import com.googlecode.imanager.client.bridge.form.IInputControl;
import com.googlecode.imanager.client.exception.RequiredException;
import com.googlecode.imanager.client.exception.ValidationException;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public abstract class InputControl extends FocusControl implements HasValidation {

    private static final long serialVersionUID = 1L;

    private boolean required;
    private String requiredMessage;
    
    private Validator validator;
    
    public InputControl() {
    }
    
    protected InputControl(int width, int height) {
        super(width, height);
    }

    @Override
    protected void onClick() {
        // don't call super.onClick()
    }

    protected void onChanged(){
        executeAction();
    }
    
    public abstract void clearInput();
    
    public abstract boolean hasInput();
    
    public final boolean isValid(){
        try {
            validate();
            return true;
        } catch (ValidationException e) {
            return false;
        }
    }
    
    public void validate() throws ValidationException {
        if (validator != null){
            validator.validate(this);
        }
        if (required && !hasInput()){
            throw new RequiredException(this, requiredMessage);
        }
    }

    public boolean isRequired() {
        return required;
    }

    public void setRequired(boolean required) {
        this.required = required;
    }

    public String getRequiredMessage() {
        return requiredMessage;
    }

    public void setRequiredMessage(String requiredMessage) {
        this.requiredMessage = requiredMessage;
    }

    public Validator getValidator() {
        return validator;
    }

    public void setValidator(Validator validator) {
        this.validator = validator;
    }

    @Override
    public InputControl clone() {
        return (InputControl) super.clone();
    }

    @Override
    protected IInputControl getBridge() {
        return (IInputControl) lookupBridge();
    }

}
